// internal/services/aliy_service.go
package services

import (
	//"gorm.io/gorm"
	"encoding/json"
	"fmt"
	"io"
	"mygin/config"
	"mygin/internal/repositories"
	"mygin/pkg/httpclient"
	"time"
)

type AliyService struct {
	repo  *repositories.TestRepository
	repos *repositories.UserRepository
}

func NewAliyService(repo *repositories.TestRepository, repos *repositories.UserRepository) *AliyService {
	return &AliyService{repo: repo, repos: repos}
}

// func NewAliyService(db *gorm.DB) *AliyService {
// 	return &AliyService{}
// }

/***
**************非curd方法区************************************/

func (s *AliyService) GetAliyByAliyname(testname string) (string, error) {
	return "okokok", nil
}

func (s *AliyService) AiChat(content string) (string, error) {
	// 创建客户端
	client := httpclient.NewCurl().SetTimeout(10 * time.Second)
	client.SetHeader("Content-Type", "application/json")
	//client.SetHeader("Authorization", "Bearer "+s.apiKey)
	client.SetHeader("Authorization", "Bearer "+string(config.GetAiALIYunKEY()))
	// 创建请求体
	requestBody := map[string]interface{}{
		"model": "qwen-plus",
		"messages": []map[string]string{
			{
				"role":    "system",
				"content": "You are a helpful assistant.",
			},
			{
				"role":    "user",
				"content": content,
			},
		},
	}
	resp, err := client.Post("https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions", requestBody)
	if err != nil {
		return "", fmt.Errorf("failed to send request: %v", err)
	}
	defer resp.Body.Close() // 确保关闭响应体

	// 读取响应体
	bodyBytes, err := io.ReadAll(resp.Body)
	if err != nil {
		return "", fmt.Errorf("failed to read response body: %v", err)
	}

	// 解析响应体
	var result map[string]interface{}
	if err := json.Unmarshal(bodyBytes, &result); err != nil {
		return "", fmt.Errorf("failed to parse response: %v", err)
	}

	// 提取AI回复内容
	if choices, ok := result["choices"].([]interface{}); ok && len(choices) > 0 {
		if firstChoice, ok := choices[0].(map[string]interface{}); ok {
			if message, ok := firstChoice["message"].(map[string]interface{}); ok {
				if aiContent, ok := message["content"].(string); ok {
					return aiContent, nil
				}
			}
		}
	}
	return string(bodyBytes), fmt.Errorf("failed to extract AI response from API result")
}
